<template>
	<div id="vip-manage-view">
		<div class="page-header">
			<h1>VIP 兑换码管理</h1>
			<a-space>
				<a-button type="primary" @click="showGenerateModal">
					<PlusOutlined />
					生成兑换码
				</a-button>
				<a-button :disabled="selectedRowKeys.length === 0" @click="showBatchOperationModal" type="default">
					<SettingOutlined />
					批量操作
				</a-button>
			</a-space>
		</div>

		<!-- 统计信息 -->
		<div class="statistics-section">
			<a-row :gutter="16">
				<a-col :span="6">
					<a-card>
						<a-statistic title="总兑换码数" :value="statistics.total" :value-style="{ color: '#1890ff' }" />
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card>
						<a-statistic title="未使用" :value="statistics.unused" :value-style="{ color: '#52c41a' }" />
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card>
						<a-statistic title="已使用" :value="statistics.used" :value-style="{ color: '#1890ff' }" />
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card>
						<a-statistic title="已过期" :value="statistics.expired" :value-style="{ color: '#f5222d' }" />
					</a-card>
				</a-col>
			</a-row>
		</div>

		<!-- 搜索和筛选 -->
		<div class="search-section">
			<a-form layout="inline" :model="searchForm" @finish="handleSearch">
				<a-row :gutter="32" style="width: 100%">
					<!-- 左侧：搜索表单区域 -->
					<a-col :xs="24" :lg="20">
						<a-row :gutter="[24, 20]">
							<a-col :xs="24" :sm="12" :md="8" :lg="8">
								<a-form-item label="兑换码">
									<a-input v-model:value="searchForm.code" placeholder="请输入兑换码" allow-clear />
								</a-form-item>
							</a-col>
							<a-col :xs="24" :sm="12" :md="8" :lg="8">
								<a-form-item label="状态">
									<a-select v-model:value="searchForm.status" placeholder="请选择状态" allow-clear>
										<a-select-option value="">全部</a-select-option>
										<a-select-option value="unused">未使用</a-select-option>
										<a-select-option value="used">已使用</a-select-option>
										<a-select-option value="expired">已过期</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
							<a-col :xs="24" :sm="12" :md="8" :lg="8">
								<a-form-item label="使用用户">
									<a-input v-model:value="searchForm.usedBy" placeholder="请输入用户名" allow-clear />
								</a-form-item>
							</a-col>
							<a-col :xs="24" :sm="12" :md="8" :lg="8">
								<a-form-item label="创建时间">
									<a-range-picker
										v-model:value="searchForm.dateRange"
										:placeholder="['开始时间', '结束时间']"
										:presets="timePresets"
										format="YYYY-MM-DD"
										style="width: 100%"
									/>
								</a-form-item>
							</a-col>
							<a-col :xs="24" :sm="12" :md="8" :lg="8">
								<a-form-item label="使用时间">
									<a-range-picker
										v-model:value="searchForm.usedDateRange"
										:placeholder="['开始时间', '结束时间']"
										:presets="timePresets"
										format="YYYY-MM-DD"
										style="width: 100%"
									/>
								</a-form-item>
							</a-col>
							<a-col :xs="24" :sm="12" :md="8" :lg="8">
								<a-form-item label="有效期">
									<a-range-picker
										v-model:value="searchForm.validDateRange"
										:placeholder="['开始时间', '结束时间']"
										:presets="timePresets"
										format="YYYY-MM-DD"
										style="width: 100%"
									/>
								</a-form-item>
							</a-col>
						</a-row>
					</a-col>

					<!-- 右侧：操作按钮区域 -->
					<a-col :xs="24" :lg="4">
						<div class="search-actions">
							<a-button type="primary" html-type="submit" :loading="loading">
								<SearchOutlined />
								搜索
							</a-button>
							<a-button @click="resetSearch">
								<ReloadOutlined />
								重置
							</a-button>
						</div>
					</a-col>
				</a-row>
			</a-form>
		</div>
		<!-- 兑换码列表 -->
		<div class="table-section">
			<div class="table-actions" v-if="selectedRowKeys.length > 0">
				<a-alert :message="`已选择 ${selectedRowKeys.length} 项`" type="info" show-icon style="margin-bottom: 12px">
					<template #action>
						<a-space>
							<a-button size="small" @click="clearSelection">取消选择</a-button>
						</a-space>
					</template>
				</a-alert>
			</div>

			<a-table
				:dataSource="redeemCodes"
				:columns="columns"
				:pagination="pagination"
				:loading="loading"
				:row-selection="{
					type: 'checkbox',
					selectedRowKeys: selectedRowKeys,
					onChange: onSelectChange,
					getCheckboxProps: (record: any) => ({
						disabled: false,
						name: record.code,
					}),
				}"
				@change="handleTableChange"
				rowKey="id"
				size="middle"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'code'">
						<a-typography-text copyable>{{ record.code }}</a-typography-text>
					</template>
					<template v-else-if="column.key === 'status'">
						<a-tag :color="getStatusColor(record.status)">
							{{ getStatusText(record.status) }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'createTime'">
						<span>{{ formatDate(record.createTime) }}</span>
					</template>
					<template v-else-if="column.key === 'validUntil'">
						<span>{{ formatDate(record.validUntil) }}</span>
					</template>
					<template v-else-if="column.key === 'usedAt'">
						<span>{{ record.usedAt ? formatDate(record.usedAt) : '-' }}</span>
					</template>
					<template v-else-if="column.key === 'usedBy'">
						<span>{{ record.usedBy || '-' }}</span>
					</template>
					<template v-else-if="column.key === 'actions'">
						<a-space>
							<a-tooltip title="查看详情">
								<a-button type="link" size="small" @click="showDetail(record)">
									<EyeOutlined />
								</a-button>
							</a-tooltip>

							<a-tooltip title="复制兑换码">
								<a-button type="link" size="small" @click="copyCode(record.code)">
									<CopyOutlined />
								</a-button>
							</a-tooltip>

							<a-tooltip title="编辑">
								<a-button type="link" size="small" @click="editCode(record)">
									<EditOutlined />
								</a-button>
							</a-tooltip>

							<a-popconfirm
								title="确定要设置此用户的VIP身份过期吗？"
								ok-text="确定"
								cancel-text="取消"
								@confirm="forceExpireVip(record.id)"
							>
								<a-tooltip title="过期VIP身份">
									<a-button type="link" size="small" danger>
										<ClockCircleOutlined />
									</a-button>
								</a-tooltip>
							</a-popconfirm>

							<a-popconfirm title="确定要删除这个兑换码吗？" @confirm="deleteCode(record.id)">
								<a-tooltip title="删除">
									<a-button type="link" size="small" danger>
										<DeleteOutlined />
									</a-button>
								</a-tooltip>
							</a-popconfirm>
						</a-space>
					</template>
				</template>
			</a-table>
		</div>

		<!-- 生成兑换码模态框 -->
		<a-modal
			v-model:open="generateModalVisible"
			title="生成VIP兑换码"
			@ok="handleGenerate"
			:confirmLoading="generateLoading"
			width="600px"
		>
			<a-form :model="generateForm" layout="vertical" ref="generateFormRef">
				<a-form-item
					label="数量"
					name="count"
					:rules="[
						{ required: true, message: '请输入生成数量' },
						{ type: 'number', min: 1, max: 100, message: '数量必须在1-100之间' },
					]"
				>
					<a-input-number
						v-model:value="generateForm.count"
						:min="1"
						:max="100"
						style="width: 100%"
						placeholder="请输入1-100之间的数量"
					/>
					<div class="form-tip">一次最多生成100个兑换码</div>
				</a-form-item>

				<a-form-item
					label="兑换码有效期"
					name="validUntil"
					:rules="[{ required: true, message: '请选择兑换码有效期' }]"
				>
					<a-date-picker
						v-model:value="generateForm.validUntil"
						style="width: 100%"
						:disabled-date="disabledDate"
						format="YYYY-MM-DD HH:mm:ss"
						show-time
						placeholder="请选择兑换码有效期"
					/>
					<div class="form-tip">兑换码本身的过期时间，过期后无法使用</div>
				</a-form-item>

				<a-form-item label="VIP卡时长" name="vipDuration" :rules="[{ required: true, message: '请输入VIP卡时长' }]">
					<a-input-number
						v-model:value="generateForm.vipDuration"
						style="width: 100%"
						:min="1"
						:max="3650"
						placeholder="请输入VIP卡时长(天数)"
						addonAfter="天"
					/>
					<div class="form-tip">用户使用兑换码后获得的VIP时长，单位为天数</div>
				</a-form-item>
				<a-form-item label="备注">
					<a-textarea
						v-model:value="generateForm.remark"
						:rows="3"
						placeholder="可选，添加备注信息"
						:maxlength="200"
						show-count
					/>
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 编辑兑换码模态框 -->
		<a-modal
			v-model:open="editModalVisible"
			title="编辑兑换码"
			@ok="handleEdit"
			:confirmLoading="editLoading"
			width="500px"
		>
			<a-form :model="editForm" layout="vertical" ref="editFormRef">
				<a-form-item label="兑换码">
					<a-input v-model:value="editForm.code" disabled />
				</a-form-item>

				<a-form-item
					label="兑换码有效期"
					name="validUntil"
					:rules="[{ required: true, message: '请选择兑换码有效期' }]"
				>
					<a-date-picker
						v-model:value="editForm.validUntil"
						style="width: 100%"
						:disabled-date="disabledDate"
						format="YYYY-MM-DD HH:mm:ss"
						show-time
						placeholder="请选择兑换码有效期"
					/>
					<div class="form-tip">兑换码本身的过期时间</div>
				</a-form-item>
				<a-form-item label="备注">
					<a-textarea v-model:value="editForm.remark" :rows="3" :maxlength="200" show-count />
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 批量操作模态框 -->
		<a-modal
			v-model:open="batchModalVisible"
			title="批量操作"
			@ok="handleBatchOperation"
			:confirmLoading="batchLoading"
			width="500px"
		>
			<div class="batch-info">
				<p>
					已选择 <strong>{{ selectedRowKeys.length }}</strong> 个兑换码
				</p>
			</div>
			<a-form :model="batchForm" layout="vertical">
				<a-form-item label="操作类型" name="operationType">
					<a-radio-group v-model:value="batchForm.operationType" class="batch-operation-grid">
						<a-row :gutter="[12, 12]" justify="center">
							<a-col :span="12">
								<a-radio value="delete" class="grid-radio">批量删除</a-radio>
							</a-col>
							<a-col :span="12">
								<a-radio value="updateExpiry" class="grid-radio">批量修改有效期</a-radio>
							</a-col>
							<a-col :span="12">
								<a-radio value="forceExpireVip" class="grid-radio">批量过期VIP身份</a-radio>
							</a-col>
							<a-col :span="12">
								<a-radio value="addRemark" class="grid-radio">批量修改备注</a-radio>
							</a-col>
						</a-row>
					</a-radio-group>
				</a-form-item>

				<a-form-item v-if="batchForm.operationType === 'updateExpiry'" label="兑换码有效期" name="validUntil">
					<a-date-picker
						v-model:value="batchForm.validUntil"
						style="width: 100%"
						:disabled-date="disabledDate"
						format="YYYY-MM-DD HH:mm:ss"
						show-time
						placeholder="请选择兑换码有效期"
					/>
					<div class="form-tip">批量修改兑换码本身的过期时间（可选）</div>
				</a-form-item>

				<a-form-item v-if="batchForm.operationType === 'updateExpiry'" label="VIP卡时长" name="vipDuration">
					<a-input-number
						v-model:value="batchForm.vipDuration"
						style="width: 100%"
						:min="1"
						:max="3650"
						placeholder="请输入VIP卡时长(天数)"
						addonAfter="天"
					/>
					<div class="form-tip">批量修改VIP卡时长，用户兑换后获得的VIP天数（可选）</div>
				</a-form-item>

				<a-form-item v-if="batchForm.operationType === 'addRemark'" label="备注" name="remark">
					<a-textarea
						v-model:value="batchForm.remark"
						:rows="3"
						:maxlength="200"
						show-count
						placeholder="请输入要添加的备注"
					/>
				</a-form-item>

				<!-- VIP身份过期操作说明 -->
				<a-form-item v-if="batchForm.operationType === 'forceExpireVip'">
					<a-alert
						message="VIP身份过期说明"
						description="此操作将直接设置所选兑换码对应用户的VIP身份过期，用户将立即失去VIP权限。注意：这不是修改兑换码本身的有效期，而是直接影响用户的VIP状态。"
						type="info"
						show-icon
					/>
				</a-form-item>
			</a-form>

			<a-alert
				v-if="batchForm.operationType === 'delete'"
				message="警告：删除操作不可恢复，请谨慎操作！"
				type="warning"
				show-icon
				style="margin-top: 12px"
			/>

			<a-alert
				v-if="batchForm.operationType === 'forceExpireVip'"
				message="警告：此操作将立即设置用户VIP身份过期，用户将失去所有VIP权限！"
				type="error"
				show-icon
				style="margin-top: 12px"
			/>
		</a-modal>

		<!-- 详情模态框 -->
		<a-modal v-model:open="detailModalVisible" title="兑换码详情" width="600px">
			<a-descriptions :column="2" bordered v-if="currentRecord">
				<a-descriptions-item label="兑换码">
					<a-typography-text copyable>{{ currentRecord.code }}</a-typography-text>
				</a-descriptions-item>
				<a-descriptions-item label="状态">
					<a-tag :color="getStatusColor(currentRecord.status)">
						{{ getStatusText(currentRecord.status) }}
					</a-tag>
				</a-descriptions-item>
				<a-descriptions-item label="创建时间">
					{{ formatDate(currentRecord.createTime) }}
				</a-descriptions-item>
				<a-descriptions-item label="兑换码的使用有效期">
					{{ formatDate(currentRecord.validUntil) }}
				</a-descriptions-item>
				<a-descriptions-item label="使用时间">
					{{ currentRecord.usedAt ? formatDate(currentRecord.usedAt) : '-' }}
				</a-descriptions-item>
				<a-descriptions-item label="使用用户">
					{{ currentRecord.usedBy || '-' }}
				</a-descriptions-item>
				<a-descriptions-item label="备注" :span="2">
					{{ currentRecord.remark || '-' }}
				</a-descriptions-item>
			</a-descriptions>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
	PlusOutlined,
	SettingOutlined,
	SearchOutlined,
	ReloadOutlined,
	EyeOutlined,
	EditOutlined,
	DeleteOutlined,
	CopyOutlined,
	ClockCircleOutlined,
} from '@ant-design/icons-vue'
import dayjs, { type Dayjs } from 'dayjs'
import {
	generateRedeemCodes,
	listVipRedeemCodeVoByPage,
	updateVipRedeemCode,
	deleteVipRedeemCode,
	batchDeleteVipRedeemCode,
	forceExpireVipRedeemCode,
	batchForceExpireVipRedeemCode,
} from '@/api/vipRedeemCodeController'

// 数据定义
const loading = ref(false)
const redeemCodes = ref<API.VipRedeemCodeVO[]>([])
const generateModalVisible = ref(false)
const editModalVisible = ref(false)
const batchModalVisible = ref(false)
const detailModalVisible = ref(false)
const generateLoading = ref(false)
const editLoading = ref(false)
const batchLoading = ref(false)

// 表格选择相关
const selectedRowKeys = ref<string[]>([])
const currentRecord = ref<API.VipRedeemCodeVO | null>(null)

// 表单引用
const generateFormRef = ref()
const editFormRef = ref()

// 搜索表单
const searchForm = reactive({
	code: '',
	status: '',
	usedBy: '',
	dateRange: null as [Dayjs, Dayjs] | null,
	usedDateRange: null as [Dayjs, Dayjs] | null,
	validDateRange: null as [Dayjs, Dayjs] | null,
})

// 时间预设配置
const timePresets = [
	{
		label: '最近一周',
		value: [dayjs().subtract(7, 'day').startOf('day'), dayjs().endOf('day')],
	},
	{
		label: '最近一个月',
		value: [dayjs().subtract(1, 'month').startOf('day'), dayjs().endOf('day')],
	},
	{
		label: '最近三个月',
		value: [dayjs().subtract(3, 'month').startOf('day'), dayjs().endOf('day')],
	},
	{
		label: '最近一年',
		value: [dayjs().subtract(1, 'year').startOf('day'), dayjs().endOf('day')],
	},
]

// 生成表单
const generateForm = reactive({
	count: 1,
	validUntil: null as Dayjs | null,
	vipDuration: null as number | null,
	remark: '',
})

// 编辑表单
const editForm = reactive({
	id: null as number | null,
	code: '',
	validUntil: null as Dayjs | null,
	remark: '',
})

// 批量操作表单
const batchForm = reactive({
	operationType: 'delete' as 'delete' | 'updateExpiry' | 'updateVipDuration' | 'addRemark' | 'forceExpireVip',
	validUntil: null as Dayjs | null,
	vipDuration: null as number | null,
	remark: '',
})

// 分页配置
const pagination = reactive({
	current: 1,
	pageSize: 10,
	total: 0,
	showSizeChanger: true,
	showQuickJumper: false,
	showTotal: (total: number) => `共 ${total} 条数据`,
})

// 表格列配置
const columns = [
	{
		title: '兑换码',
		dataIndex: 'code',
		key: 'code',
		width: 130,
		ellipsis: true,
		align: 'center' as const,
	},
	{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
		width: 80,
		align: 'center' as const,
	},
	{
		title: '创建时间',
		dataIndex: 'createTime',
		key: 'createTime',
		width: 150,
		align: 'center' as const,
	},
	{
		title: '兑换码有效期',
		dataIndex: 'validUntil',
		key: 'validUntil',
		width: 150,
		align: 'center' as const,
	},
	{
		title: 'VIP卡时长',
		dataIndex: 'vipDurationText',
		key: 'vipDurationText',
		width: 120,
		align: 'center' as const,
	},
	{
		title: 'VIP过期时间',
		dataIndex: 'vipExpireTime',
		key: 'vipExpireTime',
		width: 150,
		align: 'center' as const,
		customRender: ({ record }: { record: API.VipRedeemCodeVO }) => {
			// 只有已使用的兑换码才显示VIP过期时间
			if (record.status !== 'used' || !record.vipExpireTime) {
				return '-'
			}
			return record.vipExpireTime
		},
	},
	{
		title: '使用时间',
		dataIndex: 'usedAt',
		key: 'usedAt',
		width: 150,
		align: 'center' as const,
	},
	{
		title: '使用用户',
		dataIndex: 'usedBy',
		key: 'usedBy',
		width: 120,
		align: 'center' as const,
	},
	{
		title: '备注',
		dataIndex: 'remark',
		key: 'remark',
		ellipsis: true,
		width: 150,
	},
	{
		title: '操作',
		key: 'actions',
		width: 220,
		fixed: 'right' as const,
		align: 'center' as const,
	},
]

// 统计信息计算
const statistics = computed(() => {
	const total = redeemCodes.value.length
	const unused = redeemCodes.value.filter((item) => item.status === 'unused').length
	const used = redeemCodes.value.filter((item) => item.status === 'used').length
	const expired = redeemCodes.value.filter((item) => item.status === 'expired').length

	return { total, unused, used, expired }
})

// 初始化加载数据
onMounted(() => {
	loadRedeemCodes()
})

// 表格选择变化处理
const onSelectChange = (newSelectedRowKeys: string[]) => {
	selectedRowKeys.value = newSelectedRowKeys
}

// 清除选择
const clearSelection = () => {
	selectedRowKeys.value = []
}

// 显示批量操作模态框
const showBatchOperationModal = () => {
	if (selectedRowKeys.value.length === 0) {
		message.warning('请先选择要操作的兑换码')
		return
	}
	batchForm.operationType = 'delete'
	batchForm.validUntil = null
	batchForm.vipDuration = null
	batchForm.remark = ''
	batchModalVisible.value = true
}

// 显示详情模态框
const showDetail = (record: API.VipRedeemCodeVO) => {
	currentRecord.value = record
	detailModalVisible.value = true
}

// 复制兑换码
const copyCode = async (code: string) => {
	try {
		await navigator.clipboard.writeText(code)
		message.success('兑换码已复制到剪贴板')
	} catch (error) {
		message.error('复制失败，请手动复制')
	}
}

// 加载兑换码数据
const loadRedeemCodes = async () => {
	loading.value = true
	try {
		const queryParams: API.VipRedeemCodeQueryRequest = {
			current: pagination.current,
			pageSize: pagination.pageSize,
			code: searchForm.code || undefined,
			status: searchForm.status || undefined,
			usedBy: searchForm.usedBy || undefined,
		}

		// 处理时间范围查询
		if (searchForm.dateRange && searchForm.dateRange.length === 2) {
			queryParams.createTimeStart = searchForm.dateRange[0].startOf('day').toISOString()
			queryParams.createTimeEnd = searchForm.dateRange[1].endOf('day').toISOString()
		}

		// 处理有效期范围查询
		if (searchForm.validDateRange && searchForm.validDateRange.length === 2) {
			queryParams.validUntilStart = searchForm.validDateRange[0].startOf('day').toISOString()
			queryParams.validUntilEnd = searchForm.validDateRange[1].endOf('day').toISOString()
		}

		const res = await listVipRedeemCodeVoByPage(queryParams)
		if (res.data.code === 0 && res.data.data) {
			redeemCodes.value = res.data.data.records || []
			pagination.total = Number(res.data.data.totalRow) || 0
		} else {
			message.error(res.data.message || '加载兑换码列表失败')
		}
	} catch (error: any) {
		console.error('加载兑换码列表失败:', error)
		message.error('网络错误，请稍后重试')

		// 开发环境模拟数据
		await new Promise((resolve) => setTimeout(resolve, 500))
		const mockData = Array.from({ length: 8 }, (_, i) => ({
			id: i + 1,
			code: `VIP${Date.now()}${i.toString().padStart(3, '0')}`,
			status: ['unused', 'used', 'expired'][i % 3],
			validUntil: dayjs().add(30, 'day').toISOString(),
			usedAt: i % 3 === 1 ? dayjs().subtract(5, 'day').toISOString() : undefined,
			usedBy: i % 3 === 1 ? `user_${i}` : undefined,
			remark: `第${i + 1}批生成的兑换码`,
			createTime: dayjs().subtract(i, 'day').toISOString(),
		}))

		redeemCodes.value = mockData
		pagination.total = 50
	} finally {
		loading.value = false
	}
}

// 搜索
const handleSearch = () => {
	pagination.current = 1
	loadRedeemCodes()
}

// 重置搜索
const resetSearch = () => {
	Object.assign(searchForm, {
		code: '',
		status: '',
		usedBy: '',
		dateRange: null,
		usedDateRange: null,
		validDateRange: null,
	})
	pagination.current = 1
	loadRedeemCodes()
}

// 表格变化处理
const handleTableChange = (pag: any) => {
	Object.assign(pagination, pag)
	loadRedeemCodes()
}

// 显示生成模态框
const showGenerateModal = () => {
	generateForm.count = 1
	generateForm.validUntil = dayjs().add(30, 'day').hour(23).minute(59).second(59)
	generateForm.vipDuration = 30
	generateForm.remark = ''
	generateModalVisible.value = true
}

// 生成兑换码
const handleGenerate = async () => {
	try {
		await generateFormRef.value?.validate()
	} catch (error) {
		return
	}

	if (!generateForm.validUntil) {
		message.error('请选择兑换码有效期')
		return
	}

	if (!generateForm.vipDuration || generateForm.vipDuration < 1) {
		message.error('请设置VIP卡时长')
		return
	}

	generateLoading.value = true
	try {
		const params: API.VipRedeemCodeGenerateRequest = {
			count: generateForm.count,
			validUntil: generateForm.validUntil.toISOString(),
			vipDuration: generateForm.vipDuration,
			remark: generateForm.remark || undefined,
		}

		const res = await generateRedeemCodes(params)
		if (res.data.code === 0) {
			message.success(`成功生成 ${generateForm.count} 个兑换码`)
			generateModalVisible.value = false
			generateFormRef.value?.resetFields()
			loadRedeemCodes()
		} else {
			message.error(res.data.message || '生成兑换码失败')
		}
	} catch (error: any) {
		console.error('生成兑换码失败:', error)
		message.error('网络错误，请稍后重试')
	} finally {
		generateLoading.value = false
	}
}

// 编辑兑换码
const editCode = (record: API.VipRedeemCodeVO) => {
	editForm.id = record.id || null
	editForm.code = record.code || ''
	editForm.validUntil = record.validUntil ? dayjs(record.validUntil) : null
	editForm.remark = record.remark || ''
	editModalVisible.value = true
}

// 处理编辑
const handleEdit = async () => {
	try {
		await editFormRef.value?.validate()
	} catch (error) {
		return
	}

	if (!editForm.validUntil) {
		message.error('请选择有效期')
		return
	}

	editLoading.value = true
	try {
		const params: API.VipRedeemCodeUpdateRequest = {
			id: editForm.id || undefined,
			validUntil: editForm.validUntil.toISOString(),
			remark: editForm.remark || undefined,
		}

		const res = await updateVipRedeemCode(params)
		if (res.data.code === 0) {
			message.success('更新成功')
			editModalVisible.value = false
			editFormRef.value?.resetFields()
			loadRedeemCodes()
		} else {
			message.error(res.data.message || '更新失败')
		}
	} catch (error: any) {
		console.error('更新失败:', error)
		message.error('网络错误，请稍后重试')
	} finally {
		editLoading.value = false
	}
}

// 删除兑换码
const deleteCode = async (id: number | undefined) => {
	if (!id) {
		message.error('兑换码ID不能为空')
		return
	}

	try {
		const res = await deleteVipRedeemCode({ id })
		if (res.data.code === 0) {
			message.success('删除成功')
			loadRedeemCodes()
			// 如果当前选择包含被删除的项，清除选择
			selectedRowKeys.value = selectedRowKeys.value.filter((key) => key !== id.toString())
		} else {
			message.error(res.data.message || '删除失败')
		}
	} catch (error: any) {
		console.error('删除失败:', error)
		message.error('网络错误，请稍后重试')
	}
}

// 过期VIP身份
const forceExpireVip = async (id: number | undefined) => {
	if (!id) {
		message.error('兑换码ID不能为空')
		return
	}

	try {
		const res = await forceExpireVipRedeemCode({ id })
		if (res.data.code === 0) {
			message.success('VIP身份过期设置成功')
			loadRedeemCodes()
			// 如果当前选择包含该项，清除选择
			selectedRowKeys.value = selectedRowKeys.value.filter((key) => key !== id.toString())
		} else {
			message.error(res.data.message || 'VIP身份过期设置失败')
		}
	} catch (error: any) {
		console.error('VIP身份过期设置失败:', error)
		message.error('网络错误，请稍后重试')
	}
}

// 处理批量操作
const handleBatchOperation = async () => {
	const selectedIds: any = selectedRowKeys.value

	if (selectedIds.length === 0) {
		message.warning('请选择要操作的兑换码')
		return
	}

	batchLoading.value = true
	try {
		let res: any = null

		switch (batchForm.operationType) {
			case 'delete':
				res = await batchDeleteVipRedeemCode(selectedIds)
				if (res.data.code === 0) {
					message.success(`成功删除 ${selectedIds.length} 个兑换码`)
					clearSelection()
					loadRedeemCodes()
				} else {
					message.error(res.data.message || '批量删除失败')
				}
				break

			case 'updateExpiry':
				// 检查至少要修改一个字段
				if (!batchForm.validUntil && (!batchForm.vipDuration || batchForm.vipDuration < 1)) {
					message.error('请至少选择修改兑换码有效期或VIP时长中的一项')
					return
				}

				// 批量更新有效期和/或VIP时长（需要逐个调用更新接口）
				let successCount = 0
				for (const id of selectedIds) {
					try {
						const updateParams: any = { id }

						// 如果选择了有效期则添加到参数中
						if (batchForm.validUntil) {
							updateParams.validUntil = batchForm.validUntil.toISOString()
						}

						// 如果选择了VIP时长则添加到参数中
						if (batchForm.vipDuration && batchForm.vipDuration > 0) {
							updateParams.vipDuration = batchForm.vipDuration
						}

						const updateRes = await updateVipRedeemCode(updateParams)
						if (updateRes.data.code === 0) {
							successCount++
						}
					} catch (error) {
						console.error(`更新兑换码 ${id} 失败:`, error)
					}
				}

				if (successCount > 0) {
					let updateMessage = '成功更新 ' + successCount + '/' + selectedIds.length + ' 个兑换码的'
					const updateFields = []
					if (batchForm.validUntil) updateFields.push('有效期')
					if (batchForm.vipDuration && batchForm.vipDuration > 0) updateFields.push('VIP时长')
					updateMessage += updateFields.join('和')

					message.success(updateMessage)
					clearSelection()
					loadRedeemCodes()
				} else {
					message.error('批量更新失败')
				}
				break

			case 'addRemark':
				if (!batchForm.remark?.trim()) {
					message.error('请输入备注内容')
					return
				}

				// 批量修改备注（需要逐个调用更新接口）
				let remarkSuccessCount = 0
				for (const id of selectedIds) {
					try {
						const updateRes = await updateVipRedeemCode({
							id,
							remark: batchForm.remark,
						})
						if (updateRes.data.code === 0) {
							remarkSuccessCount++
						}
					} catch (error) {
						console.error(`更新兑换码 ${id} 备注失败:`, error)
					}
				}

				if (remarkSuccessCount > 0) {
					message.success(`成功为 ${remarkSuccessCount}/${selectedIds.length} 个兑换码添加备注`)
					clearSelection()
					loadRedeemCodes()
				} else {
					message.error('批量添加备注失败')
				}
				break

			case 'forceExpireVip':
				res = await batchForceExpireVipRedeemCode(selectedIds)
				if (res.data.code === 0) {
					message.success(`成功设置 ${selectedIds.length} 个用户的VIP身份过期`)
					clearSelection()
					loadRedeemCodes()
				} else {
					message.error(res.data.message || '批量过期VIP身份失败')
				}
				break
		}

		batchModalVisible.value = false
	} catch (error: any) {
		console.error('批量操作失败:', error)
		message.error('网络错误，请稍后重试')
	} finally {
		batchLoading.value = false
	}
}

// 获取状态颜色
const getStatusColor = (status: string | undefined) => {
	const colorMap: Record<string, string> = {
		unused: 'green',
		used: 'blue',
		expired: 'red',
	}
	return status ? colorMap[status] || 'default' : 'default'
}

// 获取状态文本
const getStatusText = (status: string | undefined) => {
	const textMap: Record<string, string> = {
		unused: '未使用',
		used: '已使用',
		expired: '已过期',
	}
	return status ? textMap[status] || status : '未知'
}

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
	if (!date) return '-'
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 禁用过去的日期
const disabledDate = (current: Dayjs) => {
	return current && current < dayjs().startOf('day')
}
</script>

<style scoped lang="scss">
#vip-manage-view {
	max-width: 100%;
	overflow-x: hidden;

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24px;

		h1 {
			margin: 0;
			color: #2d3748;
			font-size: 24px;
			font-weight: 600;
		}
	}

	.statistics-section {
		margin-bottom: 24px;

		.ant-card {
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			border-radius: 8px;

			:deep(.ant-statistic-title) {
				color: #666;
				font-size: 14px;
			}

			:deep(.ant-statistic-content) {
				font-size: 24px;
				font-weight: 600;
			}
		}
	}

	.search-section {
		background: white;
		padding: 12px;
		border-radius: 8px;
		margin-bottom: 24px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

		.ant-form-item {
			margin-bottom: 12px;
		}

		.search-actions {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 12px;
			height: 100%;
			padding: 0 8px;
			border-left: 1px solid #f0f0f0;

			@media (max-width: 1023px) {
				border-left: none;
				border-top: 1px solid #f0f0f0;
				padding: 12px 0 0 0;
				justify-content: center;
				margin-top: 12px;

				.ant-btn {
					min-width: 80px;
				}
			}

			.ant-btn {
				min-width: 70px;
			}
		} // 响应式调整
		@media (max-width: 768px) {
			padding: 12px;

			.ant-row {
				.ant-col {
					padding-bottom: 8px;
				}
			}
		}
	}

	.table-section {
		background: white;
		padding: 24px;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

		.table-actions {
			margin-bottom: 12px;
		}
	}

	:deep(.ant-table-thead > tr > th) {
		background: #f8fafc;
		font-weight: 600;
		color: #374151;
		text-align: center;
	}

	:deep(.ant-table-tbody > tr:hover > td) {
		background: #f9fafb;
	}

	// 状态标签样式
	:deep(.ant-tag) {
		border-radius: 4px;
		font-size: 12px;
		font-weight: 500;
	}

	// 操作按钮样式
	:deep(.ant-btn-link) {
		padding: 0;
		height: auto;
		font-size: 14px;

		&:hover {
			text-decoration: none;
		}
	}

	// 模态框样式优化
	:deep(.ant-modal-header) {
		border-bottom: 1px solid #f0f0f0;
		padding: 12px 24px;

		.ant-modal-title {
			font-size: 18px;
			font-weight: 600;
		}
	}

	:deep(.ant-modal-body) {
		padding: 24px;
	}

	// 表单样式
	.form-tip {
		font-size: 12px;
		color: #666;
		margin-top: 4px;
	}

	.batch-info {
		background: #f6f8fa;
		border: 1px solid #e1e4e8;
		border-radius: 6px;
		padding: 12px;
		margin-bottom: 12px;

		p {
			margin: 0;
			color: #586069;
			font-size: 14px;
		}
	}

	// 批量操作网格布局样式
	.batch-operation-grid {
		padding: 12px 8px;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;

		.ant-row {
			justify-content: center;
			width: 100%;
			max-width: 420px; // 增加最大宽度以更好利用模态框空间
		}

		.grid-radio {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 50px; // 稍微增加高度
			padding: 0 12px;
			border: 2px solid #d9d9d9;
			border-radius: 8px;
			background: #fff;
			transition: all 0.2s ease;
			margin-bottom: 0;
			text-align: center;
			cursor: pointer;
			white-space: nowrap;
			overflow: hidden;

			&:hover {
				border-color: #40a9ff;
				background: #f6ffed;
				transform: translateY(-1px);
				box-shadow: 0 4px 8px rgba(64, 169, 255, 0.2);
			}

			// 选中状态样式
			&.ant-radio-wrapper-checked {
				border-color: #1890ff;
				background: #e6f7ff;
				transform: translateY(-1px);
				box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);

				.ant-radio-inner {
					border-color: #1890ff;
				}
			}

			.ant-radio {
				margin-right: 8px;
				flex-shrink: 0;
			}

			// 文字样式
			span:not(.ant-radio) {
				font-weight: 500;
				font-size: 14px;
				flex-shrink: 0;
			}
		}
	} // 详情页面样式
	:deep(.ant-descriptions-item-label) {
		font-weight: 600;
		color: #374151;
	}

	:deep(.ant-descriptions-item-content) {
		color: #6b7280;
	}

	// 分页样式
	:deep(.ant-pagination) {
		margin-top: 12px;
		text-align: right;
	}
}
</style>
